package top.pengdong.pictureShare.userAuth.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.pengdong.pictureShare.common.model.SysConstant;
import top.pengdong.pictureShare.common.pojo.SecurityUser;
import top.pengdong.pictureShare.userAuth.dao.TRoleDao;
import top.pengdong.pictureShare.userAuth.dao.TUserAuthsDao;
import top.pengdong.pictureShare.userAuth.dao.TUserRoleDao;
import top.pengdong.pictureShare.userAuth.dao.TUsersDao;
import top.pengdong.pictureShare.userAuth.entity.TRoleEntity;
import top.pengdong.pictureShare.userAuth.entity.TUserRoleEntity;
import top.pengdong.pictureShare.userAuth.entity.TUsersEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 公众号：码猿技术专栏
 * UserDetailsService的实现类，从数据库加载用户的信息，比如密码、角色。。。。
 */
@Slf4j
@Service(value = "jwtTokenUserDetailsService")
@Primary
public class JwtTokenUserDetailsService implements UserDetailsService {

    @Autowired
    private TUserRoleDao tUserRoleDao;

    @Autowired
    private TRoleDao tRoleDao;

    @Autowired
    private TUsersDao tUsersDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // System.out.println("用户登录操作");
        TUsersEntity user = tUsersDao.findTUserByUsername(username);
        log.info("用户进行登录:{}" + user);
        if (Objects.isNull(user))
            throw new UsernameNotFoundException("用户不存在！");
        //角色 同时 查看启用状态
        List<TUserRoleEntity> userRoles = tUserRoleDao.selectList(
                new QueryWrapper<TUserRoleEntity>()
                        .eq("user_id", user.getId())
                        .eq("status", 1)
        );
        //该用户的所有权限（角色）
        List<String> roles=new ArrayList<>();
        for (TUserRoleEntity userRole : userRoles) {
            TRoleEntity tRoleEntity = tRoleDao.selectById(userRole.getRoleId());
            roles.add(SysConstant.ROLE_PREFIX + tRoleEntity.getName());
            // System.out.println(roles.get(0));
        }
        return SecurityUser.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                //将角色放入authorities中
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles,String.class)))
                .build();
    }
}
